#include <unistd.h>
#include <math.h>
#include "./lib/pwm_sysfs.h"

int main()
{
    // 这个程序实现按指数级变化的PWM占空比调节LED亮度
    // 因为人的眼睛对亮度的感知是对数关系，而非线性关系
    int pwm_chip = 0;    // PWM芯片号
    int pwm_channel = 0; // PWM通道号
    char input[16];

    printf("Set PWM chip number (default 0): ");
    fgets(input, sizeof(input), stdin);
    if (sscanf(input, "%d", &pwm_chip) != 1)
        return 0; // 输入无效，退出
    printf("Set PWM channel number (default 0): ");
    fgets(input, sizeof(input), stdin);
    if (sscanf(input, "%d", &pwm_channel) != 1)
        return 0; // 输入无效，退出
    printf("Using PWM chip %d, channel %d\n", pwm_chip, pwm_channel);
    pwm_t pwm;
    if (pwm_open(&pwm, pwm_chip, pwm_channel) != 0)
    {
        perror("Failed to open PWM");
        return -1;
    }

    // 设置PWM参数
    long long period_ns = 1000000; // 1ms周期，频率1kHz
    int duty = 0;
    pwm_operate(&pwm, period_ns, duty, PWM_POLARITY_NORMAL);
    pwm_enable(&pwm, 1); // 使能PWM

    // 指数级变化占空比
    while(1)
    {
        for (int i = 0; i <= 0xFF; i++) // 255级调光
        {
            // gamma校正
            double gamma = 2.2;
            double normalized = (double)i / 255.0;
            double corrected = pow(normalized, gamma);
            duty = (int)(corrected * period_ns);
            pwm_set_duty_cycle(&pwm, duty);
            printf("Duty cycle set to %d ns\n", duty);
            usleep(10000); // 10ms延时
        }
        for (int i = 0xFF; i >= 0; i--)
        {
            // gamma校正
            double gamma = 2.2;
            double normalized = (double)i / 255.0;
            double corrected = pow(normalized, gamma);
            duty = (int)(corrected * period_ns);
            pwm_set_duty_cycle(&pwm, duty);
            printf("Duty cycle set to %d ns\n", duty);
            usleep(10000); // 10ms延时
        }
    }

    return 0;
}
